<template>
  <div>
    <Invoice
      ref="invoice"
      v-if="showDetails"
      :japanLine="japanLine"
      :order-type="orderType"
      :channelFormLeft="channelFormLeft"
      :waybill-id="id"
      :publicData="publicData"
      :invoiceInfoData="invoiceInfoData"
      :statusEnable.sync="statusEnable"
      :waybill-code="randomCode"
      :oldShipmentIds.sync="oldShipmentIds"
      :oldReferenceIds.sync="oldReferenceIds"
    />

    <PackingList
      v-if="showDetails && channelFormLeft.shippingWay !== '99'"
      ref="packingList"
      :packingList="packingInfo"
      :statusEnable.sync="statusEnable"
      @resetPacking="resetPacking"
    />

    <!-- <div class="text-center margin-tb">
      <el-button type="primary" @click="submitForm" size="mini">
        保存
      </el-button>
    </div> -->
  </div>
</template>

<script>
import Invoice from "./components/Invoice.vue";
import PackingList from "./components/PackingList.vue";
import { mapGetters } from "vuex";
import { ajax } from "@/store/yg/common/utils";
import { clone } from "@/utils/clone";
import * as constant from "@/store/yg/common/constant";
import axios from "axios";

export default {
  name: "TabPane",
  components: {
    Invoice,
    PackingList
  },
  props: {
    orderType: {
      type: String,
      default: "quickOrder"
    }
  },
  data() {
    return {
      statusEnable: false,
      japanLine: [16, 17, 99, 115, 229, 227, 226, 136, 115, 88, 84, 34, 33], // 日本专线
      channelFormLeft: {},
      showDetails: false,
      address: "",
      id: "",
      randomCode: "",
      fileList: [
        {
          file: ""
        }
      ],
      publicData: {
        currencyMap: {}
      },
      invoicesAndPackingLis: {},
      list: null,
      waybillRender: {},
      fbaRules: ["shipmentId", "referenceId"],
      rules: [
        "sku",
        "declareNameCn",
        "declareNameEn",
        "brand",
        "material",
        "purpose",
        "customsCode",
        "model",
        "num",
        "measurementUnit",
        "purchasingPrice",
        "sku",
        "declareValue",
        "imgUrl"
      ],
      jpRules: [
        "distributionMaterialCount",
        "productLotCount",
        "sellpriceScreenshot",
        "incomeScreenshot"
      ],
      params: {
        shipmentId: "Shipment ID",
        referenceId: "Reference ID",
        sku: "SKU",
        declareNameCn: "中文品名",
        declareNameEn: "英文品名",
        brand: "品牌",
        material: "材质",
        purpose: "用途",
        customsCode: "海关编码",
        model: "型号",
        num: "SKU个数",
        measurementUnit: "单位",
        purchasingPrice: "采购价格",
        declareValue: "申报价格",
        imgUrl: "SKU图片",
        distributionMaterialCount: "配送料",
        productLotCount: "出品手数料",
        sellpriceScreenshot: "售价截图",
        incomeScreenshot: "收益截图"
      },
      packingParams: {
        weight: "单箱毛重",
        length: "单箱长度",
        width: "单箱宽度",
        height: "单箱高度",
        startNumNo: "箱号",
        sku: "SKU",
        num: "SKU数量"
      },

      oldShipmentIds: [],
      oldReferenceIds: [],

      packingRules: ["startNumNo", "weight", "length", "width", "height"],
      customerShipperMap: [],
      customerImporter: [],
      invoiceInfo: {
        oldPackingInfo: [],
        oldTableData: [],
        tableData: [{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}]
      },
      packingInfo: [],
      invoiceInfoData: {
        oldPackingInfo: [],
        oldTableData: [],
        declareValueCurrency: "", // 币种
        tableData: [{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}]
      }
    };
  },

  computed: {
    isJapan() {
      return (
        this.channelFormLeft &&
        this.channelFormLeft.inStockChannel &&
        this.japanLine.includes(parseInt(this.channelFormLeft.inStockChannel))
      );
    }
  },
  created() {
    const id = this.$route.query.waybillId;
    this.randomCode = this.$route.query.randomCode;
    if (id) {
      this.id = id;
      this.getWaybillInfo();
    }
  },
  mounted() {
    // this.id = this.$route.query.waybillId;
    this.init();
    console.log("this.$refs.invoice.timer :>> ", this.$refs.invoice);
  },
  destroyed() {
    let str = "";
    if (this.id) {
      str = this.id;
    } else {
      str = this.randomCode;
    }
    sessionStorage.removeItem("channelFormLeft");
    sessionStorage.removeItem(`tableInvoice-${str}`);
    this.packingInfo = [];
    this.invoiceInfoData = {};
    console.log("this.$refs.invoice.timer :>> ", this.$refs.invoice);
  },
  methods: {
    async init() {},
    resetPacking() {
      console.log("重置装箱单 :>> ");
      this.$refs.invoice.resetPacking();
    },
    // 数据回显
    getWaybillInfo() {
      var param = {};

      param["id"] = this.id;
      ajax("getWaybillInfo", param).then(
        res => {
          console.log(res);
          if (res.code == 200) {
            // console.log('res :>> ', this.$refs.packingList)
            const waybill = res.data;
            // 出库后- 箱单重量、长、宽、高不允许修改
            if (waybill.status > 40) {
              this.statusEnable = true;
            }
            this.liquidationInvoiceList = res.data2.liquidationInvoiceList;
            this.publicData.currencyMap = res.data2.currencyMap;
            this.publicData.skuUnitMap = res.data2.skuUnitMap;
            this.oldShipmentIds = res.data2.oldShipmentIds;
            this.oldReferenceIds = res.data2.oldReferenceIds;
            this.channelFormLeft = waybill;
            console.log("this.channelFormLeft :>> ", this.channelFormLeft);
            console.log("waybill :>>res------------- ", res);
            console.log(
              "waybill.dispatchAddressCode :>> ",
              waybill.dispatchAddressCode
            );
            console.log("waybill.inStockChannel :>> ", waybill.inStockChannel);

            this.sortData({
              data: waybill,
              liquidationInvoices: waybill.liquidationInvoices,
              packingLists: res.data2["packingListmMap"]
            });
            this.showDetails = true;
          }
        },
        error => {
          console.log(error);
        }
      );

      // this.initCurryOptions("currencyTypeSource");
    },

    // initCurryOptions(bean) {
    //   var uri = "/api/entry/source?bean=" + bean;
    //   axios.post(constant.API_SERVER + uri).then(
    //     res => {
    //       this.publicData.currencyMap = res.data;
    //       this.showDetails = true;
    //     },
    //     error => {
    //       console.info(error);
    //     }
    //   );
    // },
    sortData(waybill) {
      console.log("waybill :>> ", waybill);
      // invoice
      if (
        null != waybill.liquidationInvoices &&
        waybill.liquidationInvoices.length > 0
      ) {
        const d = clone(waybill.liquidationInvoices);
        for (const i of d) {
          //  if (i.isCharged === "1") {
          //   i.isCharged = "是";
          // } else {
          //   i.isCharged = "否";
          // }

          if (i.sellpriceScreenshot) {
            i.sellPriceScreenshot = i.sellpriceScreenshot;
          }
        }

        // this.$refs.invoice.invoiceInfoData.tableData =
        //   waybill.liquidationInvoices;
        this.invoiceInfoData.tableData = clone(d);
        this.invoiceInfoData.oldTableData = clone(d);
        this.invoiceInfo.tableData = clone(d);
        this.invoiceInfo.oldTableData = clone(d);
        console.log("waybill.packingLists :>> ", waybill.packingLists);
        // 同步箱单
        this.$nextTick(() => {
          if (waybill.packingLists) {
            // 存在箱单信息
            console.log("this.$children :>> ", this.$children);
            setTimeout(() => {
              this.$refs.invoice.IntegratePackingData(waybill.packingLists);
            });
          } else {
            // 不存在箱单信息 根据发票生成
            console.log("上传信息不存在箱单信息");
            setTimeout(() => {
              this.$refs.invoice.IntegrateInvoiceData();
            });
          }
        });
      }
    },

    checInvoiceInfoAndPackingInfo(packingList, skuList) {
      console.log(
        "this.channelFormLeft.purposeWarehouseType :>> ",
        this.channelFormLeft.purposeWarehouseType
      );
      const isFBA = this.channelFormLeft.purposeWarehouseType === 100;

      let rules = [...this.rules];
      if (isFBA) {
        rules = [...this.fbaRules, ...rules];
      }
      if (this.isJapan) {
        rules = [...rules, ...this.jpaRules];
      }
      console.log("rules :>> ", rules);
      if (!isNoEmptyObject(this.invoiceInfo)) {
        this.$message.error("请填写发票数据！");
        return false;
      }
      for (const [i, e] of this.invoiceInfo.tableData.entries()) {
        for (const j of rules) {
          if (isNoEmptyObject(e) && !e[j]) {
            if (j === "declareValue" && this.isJapan) {
              this.$message.error(`请填写第${i + 1}行 必填数据 ASIN售价`);
            } else {
              this.$message.error(
                `请填写第${i + 1}行 必填数据 ${this.params[j]}`
              );
            }

            return false;
          }
        }
      }
      // 校验箱单
      if (
        this.channelFormLeft.shippingWay !== "99" &&
        packingList &&
        packingList.length > 0
      ) {
        for (const [i, e] of packingList.entries()) {
          for (const j of this.packingRules) {
            if (isNoEmptyObject(e) && !e[j]) {
              this.$message.error(
                `请填写箱号${e.startNumNo}  ${this.packingParams[j]}`
              );
              return false;
            }
          }
          for (const k of e.packSkuList) {
            if (!k.sku) {
              this.$message.error(`请填写箱号${e.startNumNo} SKU`);
            }
            if (!k.num) {
              this.$message.error(`请填写箱号${e.startNumNo} SKU数量`);
            }
          }
        }

        for (const i of skuList) {
          if (parseInt(i.skuNum) !== parseInt(i.packingNum)) {
            this.$message.error(`${i.skuName} 装箱数量与发票填写个数不一致`);
            return false;
          }
        }
      }

      return true;
    },

    async upload(e, index) {
      const file = e.target.files[0]; // target事件
      const isEXCEL =
        file.type === "application/vnd.ms-excel" ||
        file.type ===
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

      if (!isEXCEL) {
        this.$message.error("上传文件只能是EXCEL文件!");
        return false;
      }

      // 提交上传
      if (await this.uploadFn(file)) {
        this.fileList[index].file = file;
        this.fileList[index].name = file.name;
        if (this.fileList.length - 1 === index) {
          this.fileList.push({
            file: "",
            name: ""
          });
        }
      }
    },
    async submitForm() {
      console.log(
        "this.channelFormLeft :>> ",
        this.channelFormLeft.isBuyInsurance
      );

      // 箱单信息
      const packingList = [];
      const skuList = [];
      for (const i of this.packingInfo) {
        for (const j of i.tableData) {
          const obj = {
            waybillId: "",
            shipmentId: j.shipmentId,
            startNumNo: j.cartonNo,
            endNumNo: j.cartonNo,
            length: j.length,
            width: j.width,
            height: j.height,
            weight: j.grossWeight,

            packSkuList: [
              {
                sku: j.skuName,
                num: j.skuNum
              }
            ]
          };
          packingList.push(obj);
        }
        for (const i of i.filterData) {
          skuList.push(i);
        }
      }

      if (!this.checInvoiceInfoAndPackingInfo(packingList, skuList)) {
        return false;
      }
      // 件数需要 与装箱数相等  快递除外 待出库之前 取客户预报数
      if (
        this.channelFormLeft.shippingWay !== "99" &&
        this.channelFormLeft.customerTotalPackages !== packingList.length &&
        this.channelFormLeft.status <= 40
      ) {
        this.$message.error("客户下单件数和装箱单数量不匹配");
        return;
      }
      // 件数需要 与装箱数相等  快递除外 待出库之前 取入库件数
      if (
        this.channelFormLeft.shippingWay !== "99" &&
        this.channelFormLeft.inStockTotalPackages !== packingList.length &&
        this.channelFormLeft.status > 40
      ) {
        this.$message.error("入库件数和装箱单数量不匹配");
        return;
      }

      this.saveWaybill({ packingList });
    },

    async saveWaybill({ packingList }) {
      // shippingWay
      const invoiceList = [];

      if (this.invoiceInfo.tableData) {
        for (const i of this.invoiceInfo.tableData) {
          if (i.sku) {
            invoiceList.push(i);
          }
        }
      }

      const liquidationInvoices = {
        liquidationInvoices: invoiceList
      };

      const packingLists = {
        packingLists: packingList
      };

      let seaAirWaybillCreate = {};

      if (this.channelFormL.shippingWay === "99") {
        seaAirWaybillCreate = Object.assign(liquidationInvoices);
      } else {
        seaAirWaybillCreate = Object.assign(liquidationInvoices, packingLists);
      }
      // TODO
      const data = ajax("", seaAirWaybillCreate);

      if (data.code === 200) {
        this.$message({
          type: "success",
          message: "提交成功！"
        });
        this.$router.push({ name: "WaybillList" });
      } else {
        this.$message.error(data.message);
      }
    }
  }
};
</script>

<style lang="scss">
#selectChannel {
  .el-card__body {
    padding: 0;
  }
  .el-select {
    width: 100%;
  }
}

.icon-question {
  font-size: 18px;
  margin-left: 10px;
}
.upload-input {
  position: relative;
  display: inline-block;
  background: #d0eeff;
  border: 1px solid #99d3f5;
  border-radius: 4px;
  padding: 4px 12px;
  overflow: hidden;
  color: #1e88c7;
  text-decoration: none;
  text-indent: 0;
  line-height: 20px;
  input {
    position: absolute;
    font-size: 100px;
    right: 0;
    top: 0;
    opacity: 0;
  }
}
</style>
